<template>
  <div class="my-submissions">
    <div class="content-wrapper">
      <h1 class="page-title">我的提交记录</h1>

      <el-card v-loading="loading">
        <el-table :data="submissions" style="width: 100%">
          <el-table-column prop="questionnaire.title" label="问卷标题" min-width="200">
            <template #default="{ row }">
              <el-link type="primary" @click="handleDetail(row)">
                {{ row.questionnaire?.title }}
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="提交时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                link
                @click="handleViewAnswers(row)"
              >
                查看答案
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 答案详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentQuestionnaire?.title"
        width="600px"
      >
        <div class="answers-content">
          <div v-for="(answer, index) in parsedAnswers" :key="index" class="answer-item">
            <div class="question">{{ index + 1 }}. {{ answer.question }}</div>
            <div class="answer">
              <template v-if="Array.isArray(answer.answer)">
                <div v-for="(item, i) in answer.answer" :key="i">
                  {{ item }}
                </div>
              </template>
              <template v-else>
                {{ answer.answer }}
              </template>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const submissions = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const currentQuestionnaire = ref(null)
const currentAnswers = ref(null)

const parsedAnswers = computed(() => {
  if (!currentAnswers.value) return []
  try {
    const answers = JSON.parse(currentAnswers.value)
    return answers.map(a => ({
      question: a.questionTitle,
      answer: a.answer
    }))
  } catch (e) {
    return []
  }
})

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const loadSubmissions = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/questionnaire/my-submissions', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    if (res.code === 200) {
      submissions.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载提交记录失败:', error)
  } finally {
    loading.value = false
  }
}

const handleDetail = (row) => {
  router.push(`/front/questionnaires/${row.questionnaireId}`)
}

const handleViewAnswers = (row) => {
  currentQuestionnaire.value = row.questionnaire
  currentAnswers.value = row.answers
  dialogVisible.value = true
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadSubmissions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadSubmissions()
}

const loadSubmission = async () => {
  try {
    const id = route.query.id
    if (!id) return
    
    const res = await request.get(`/api/questionnaire/my-submissions/${id}`)
    if (res.code === 200) {
      currentQuestionnaire.value = res.data.questionnaire
      currentAnswers.value = res.data.answers
    }
  } catch (error) {
    console.error('加载提交记录失败:', error)
    ElMessage.error('加载提交记录失败')
  }
}

onMounted(() => {
  loadSubmissions()
  loadSubmission()
})
</script>

<style lang="scss" scoped>
.my-submissions {
  .content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .page-title {
    font-size: 28px;
    color: #303133;
    margin-bottom: 30px;
    text-align: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .answers-content {
    max-height: 60vh;
    overflow-y: auto;
    padding: 0 20px;

    .answer-item {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .question {
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;
      }

      .answer {
        color: #606266;
        line-height: 1.6;
      }
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .my-submissions {
    .content-wrapper {
      padding: 10px;
    }

    .page-title {
      font-size: 24px;
      margin-bottom: 20px;
    }
  }
}
</style> 